import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router/index'

/* 请求配置 */
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json; charset=UTF-8'
  },
  validateStatus: function (status) {
    if (status === 401) {
      ElMessage.error({ message: '验证失败' })
      window.sessionStorage.clear()
      router.push('/login')
    }
    if (status === 403) {
      ElMessage.error({ message: '暂无权限' })
    }
    if (status === 500) {
      ElMessage.error({ message: '系统错误' })
    }
    return status >= 200 && status < 300
  }
})

/* 请求前拦截 */
service.interceptors.request.use(config => {
  // mock的请求地址为项目启动时的服务地址
  config.baseURL = config.url.substring(0, 5) === '/mock' ? import.meta.env.VITE_MOCK_URL : import.meta.env.VITE_BASE_URL
  config.headers.Authorization = window.sessionStorage.getItem('token')
  return config
}, error => {
  ElMessage.error({ message: '请求超时!' })
  return Promise.reject(error)
})

/* 响应拦截 */
service.interceptors.response.use(response => {
  const res = response.data
  if (res.code !== 200) {
    ElMessage.error(res.msg || { message: '系统错误' })
    return Promise.reject(new Error('Error'))
  } else {
    return res
  }
}, error => {
  return Promise.reject(error)
})

export default service
